import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Container,
  Paper,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Button,
  Alert,
  Tabs,
  Tab,
} from '@mui/material';
import { format } from 'date-fns';
import { apiRequest, API_PATHS } from '../config/api';

interface Order {
  _id: string;
  quantity: number;
  totalPrice: number;
  status: 'completed' | 'cancelled';
  createdAt: string;
  movie: {
    title: string;
    showtime: string;
    price: number;
  };
}

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

function TabPanel(props: TabPanelProps) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      {...other}
    >
      {value === index && children}
    </div>
  );
}

const OrderList: React.FC = () => {
  const navigate = useNavigate();
  const [orders, setOrders] = useState<Order[]>([]);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [tabValue, setTabValue] = useState(0);

  const fetchOrders = async () => {
    try {
      const data = await apiRequest(API_PATHS.ORDERS);
      setOrders(data);
    } catch (error: any) {
      setError(error?.message || '获取订单列表失败');
    }
  };

  useEffect(() => {
    fetchOrders();
  }, []);

  const handleCancelOrder = async (orderId: string) => {
    try {
      await apiRequest(API_PATHS.CANCEL_ORDER(orderId), {
        method: 'POST'
      });
      setSuccess('订单取消成功');
      fetchOrders(); // 刷新订单列表
    } catch (error: any) {
      setError(error?.message || '取消订单失败');
    }
  };

  const canCancelOrder = (showtime: string) => {
    const now = new Date();
    const movieTime = new Date(showtime);
    return now < movieTime;
  };

  const handleTabChange = (_event: React.SyntheticEvent, newValue: number) => {
    setTabValue(newValue);
  };

  const renderOrderTable = (status: 'completed' | 'cancelled') => {
    const filteredOrders = orders.filter(order => order.status === status);

    return (
      <TableContainer sx={{
        background: 'rgba(255, 255, 255, 0.05)',
        borderRadius: '8px',
        '& .MuiTableCell-root': {
          color: 'white',
          borderColor: 'rgba(255, 255, 255, 0.1)',
        },
        '& .MuiTableRow-root:hover': {
          backgroundColor: 'rgba(255, 255, 255, 0.1)',
        },
      }}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>电影名称</TableCell>
              <TableCell align="right">数量</TableCell>
              <TableCell align="right">总价</TableCell>
              <TableCell>放映时间</TableCell>
              <TableCell>下单时间</TableCell>
              <TableCell>操作</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {filteredOrders.map((order) => (
              <TableRow key={order._id}>
                <TableCell>{order.movie.title}</TableCell>
                <TableCell align="right">{order.quantity}张</TableCell>
                <TableCell align="right">¥{order.totalPrice.toFixed(2)}</TableCell>
                <TableCell>{format(new Date(order.movie.showtime), 'yyyy-MM-dd HH:mm')}</TableCell>
                <TableCell>{format(new Date(order.createdAt), 'yyyy-MM-dd HH:mm')}</TableCell>
                <TableCell>
                  <Button
                    variant="outlined"
                    size="small"
                    onClick={() => navigate(`/order/${order._id}`)}
                    sx={{
                      mr: 1,
                      color: '#64b5f6',
                      borderColor: '#64b5f6',
                      '&:hover': {
                        borderColor: '#1976d2',
                        backgroundColor: 'rgba(25, 118, 210, 0.08)',
                      },
                    }}
                  >
                    查看
                  </Button>
                  {status === 'completed' && canCancelOrder(order.movie.showtime) && (
                    <Button
                      variant="outlined"
                      color="error"
                      size="small"
                      onClick={() => handleCancelOrder(order._id)}
                      sx={{
                        color: '#f44336',
                        borderColor: '#f44336',
                        '&:hover': {
                          borderColor: '#d32f2f',
                          backgroundColor: 'rgba(211, 47, 47, 0.08)',
                        },
                      }}
                    >
                      取消
                    </Button>
                  )}
                </TableCell>
              </TableRow>
            ))}
            {filteredOrders.length === 0 && (
              <TableRow>
                <TableCell colSpan={6} align="center" sx={{ py: 3 }}>
                  <Typography color="rgba(255, 255, 255, 0.7)">
                    暂无订单
                  </Typography>
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </TableContainer>
    );
  };

  return (
    <Container sx={{
      minHeight: '100vh',
      position: 'relative',
      '&::before': {
        content: "''",
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        background: 'linear-gradient(135deg, #0a192f 0%, #203a43 100%)',
        zIndex: -2,
      },
      '&::after': {
        content: "''",
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.03'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`,
        backgroundRepeat: 'repeat',
        opacity: 0.3,
        zIndex: -1,
      }
    }}>
      <Typography variant="h4" component="h1" gutterBottom sx={{
        mt: 4,
        mb: 4,
        color: 'white',
        textAlign: 'center',
        fontWeight: 'bold',
        textShadow: '2px 2px 4px rgba(0,0,0,0.3)'
      }}>
        我的订单
      </Typography>

      {error && <Alert severity="error" sx={{ mb: 2, bgcolor: 'rgba(211, 47, 47, 0.1)', color: 'white' }}>{error}</Alert>}
      {success && <Alert severity="success" sx={{ mb: 2, bgcolor: 'rgba(46, 125, 50, 0.1)', color: 'white' }}>{success}</Alert>}

      <Paper sx={{
        mb: 4,
        background: 'rgba(255, 255, 255, 0.05)',
        backdropFilter: 'blur(10px)',
        borderRadius: '16px',
        border: '1px solid rgba(255, 255, 255, 0.1)'
      }}>
        <Tabs
          value={tabValue}
          onChange={handleTabChange}
          centered
          sx={{
            '& .MuiTab-root': {
              color: 'rgba(255, 255, 255, 0.7)',
              '&.Mui-selected': {
                color: 'white',
              }
            },
            '& .MuiTabs-indicator': {
              backgroundColor: '#1976d2'
            }
          }}
        >
          <Tab label="已完成订单" />
          <Tab label="已取消订单" />
        </Tabs>
      </Paper>

      <TabPanel value={tabValue} index={0}>
        {renderOrderTable('completed')}
      </TabPanel>
      <TabPanel value={tabValue} index={1}>
        {renderOrderTable('cancelled')}
      </TabPanel>
    </Container>
  );
};

export default OrderList;